<?php

namespace app\api\controller\v1\member;


use app\api\controller\v1\Member;
use think\Db;

/**
 * 用户信息控制器
 * Class User
 * @package app\api\controller\v1\member
 */
class User extends Member{
    /**
     * 获取当前用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $info = (array)$this->member;
        $info['brief'] = Db::name('SystemBrief')->select();
        $this->success('用户信息',$info);
    }

    /**
     * 修改个人资料
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function save()
    {
        $data = ['headimg' => $this->request->post('headimg'),
            'nickname' => $this->request->post('nickname'),
            'phone' => $this->request->post('phone')];

        if(empty($data['headimg'])){
            unset($data['headimg']);
        }
        if(empty($data['nickname'])){
            unset($data['nickname']);
        }
        if(empty($data['phone'])){
            unset($data['phone']);
        }
        if(empty($data)){
            $this->error('数据有误');
        }

        if(isset($data['phone'])){
            $info = Db::name('Member')->where(['phone'=>$data['phone']])->find();
            if(!$info){
                $smscode = $this->request->post('smscode');
                //验证手机验证码
                $cache = cache($cachekey = "send_register_sms_{$data['phone']}");
                if(!isset($cache['captcha']) || $cache['captcha'] != $smscode){
                    $this->error('短信验证码错误！');
                }
            }else{
                unset($data['phone']);
            }
        }

        $re = Db::name('Member')->where(['id'=>$this->mid])->update($data);
        if($re){
            $this->success('修改成功');
        }else{
            $this->error('系统繁忙');
        }
    }
}